<?php

namespace app\api\controller;


use app\common\controller\Api;
use think\Config;
use think\Exception;

/**
 * 聊天模块
 *
 */
class Chat extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    protected $failException = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\apicompany\model\Chat();
        $this->modelFriend = new \app\apicompany\model\ChatFriend();
        $this->modelPersonageUser = new \app\apicompany\model\PersonageUser();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }


    /**
     * 发送聊天内容
     * @return void
     */
    public function add()
    {

        $input = input('post.');
//        $this->validate($input, ChatValidate::class . '.add');
        try {
            $id = $this->auth->getUserinfo()['id'];
            $result = $this->model->insertGetId([
                'sender_id' =>  $input['receive_id'],
                'receive_id' => $id,
                'content' => htmlentities($input['content']),
                'createtime' => time(), 'updatetime' => time(),
                'content_type'=> $input['content_type'] ?? 1,
            ]);
            if (!$result) {
                throw new Exception("写入聊天失败");
            }
            $find = $this->modelFriend
                ->where(['sender_id' => $input['receive_id'], 'receive_id' => $id ])
                ->find();
            if (empty($find)) {
                $res = $this->modelFriend->insert([
                    'sender_id' => $input['receive_id'],//公司
                    'receive_id' => $id,
                    'enterprise_invite_id' => $input['enterprise_invite_id'],
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
                if (!$res) {
                    throw new Exception("写入聊天好友失败");
                }
            }
            $this->success('ok', ['id' => $id, 'receive_id' => $input['receive_id']]);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * 获取聊天窗口时聊天内容
     * @return void
     */
    public function info()
    {
        $input = input('post.');
//        $this->validate($input, ChatValidate::class . '.info');
        try {
            $id = $this->auth->getUser()['id'];      //当前用户id

            $pageArr = [
                'page' => 1,
                'page_limit' => 30,
            ];
            $pageArr = array_merge($pageArr, $input);
            $list = $this->model->alias('c')
                ->join("user s", "c.sender_id=s.id", "left")
                ->join("user r", "c.receive_id=r.id", "left")
                ->where(['c.receive_id' => $id, 'c.sender_id' => $input['receive_id']])
                ->field(["s.id as sender_id", "s.username as sender_name", "s.avatar as sender_images", "r.id as receive_id", "r.username as receive_name", "r.avatar as receive_img", "c.*"])
                ->order('c.createtime', 'desc')
                ->paginate(['page' => $pageArr['page'] ?: 1, 'list_rows' => $pageArr['page_limit'] ?: 10]);
            $this->model
                ->where('sender_id', $id)
                ->where('receive_id', $input['receive_id'])
                ->where('is_read', 0)->update(['is_read' => 1]);
            $list['enterprise_invite'] = $this->modelFriend->alias('c')
                ->join('enterprise_invite e','e.id=c.enterprise_invite_id')
                ->where(['c.receive_id' => $id, 'c.sender_id' => $input['receive_id']])
                ->field('e.*')
                ->find();

            $this->success('ok', $list);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

    }


    /**
     * 消息列表
     * @return void
     */
    public function list()
    {
        $input = input();
        try {
            $pageArr = [
                'page' => 1,
                'page_limit' => 30,
            ];
            $pageArr = array_merge($pageArr, $input);
            $list = $this->modelFriend->alias('m')
                ->where('m.receive_id', $this->auth->getUserinfo()['id'])
                ->join('enterprise_user u','u.user_id=m.sender_id')
                ->field('m.*,u.name,u.username,u.mobile,u.companyimages')
                ->order('createtime', 'desc')
                ->paginate(['page' => $pageArr['page'] ?: 1, 'list_rows' => $pageArr['page_limit'] ?: 10]);
        
            foreach ($list->items() as &$v) {
                $v['count'] = $this->model
                    ->where('sender_id', $v['receive_id'])
                    ->where('receive_id', $v['sender_id'])
                    ->where('is_read', 0)
                    ->count('id');
            }
            $this->success('ok', $list);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
    
    /**
     * 发送简历
     * @return void
     */
    public function  resume_send(){
        $input = input();
        try {
            $this->modelFriend->where('id', $input['id'])->update([
                'type' => 2
            ]);
            $this->success('ok');
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

}